package com.medisoft.filter;

import java.io.IOException;
import javax.servlet.*;
import org.javalite.activejdbc.Base;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;

public class ActiveJdbcFilter implements Filter {

    private static final Logger logger = LoggerFactory.getLogger(ActiveJdbcFilter.class);

    private static String jndiName;

    public void init(FilterConfig config) throws ServletException {

        jndiName = config.getInitParameter("jndiName");
        if (jndiName == null) {
            throw new IllegalArgumentException("debe configurar el parametro jndiName");
        }
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        long before = System.currentTimeMillis();
        try {
            Base.open(jndiName);
            Base.openTransaction();
            chain.doFilter(req, resp);
            Base.commitTransaction();
        } catch (IOException e) {
            Base.rollbackTransaction();
            throw e;
        } catch (ServletException e) {
            Base.rollbackTransaction();
            throw e;
        } finally {

            Base.close();
        }
        logger.info("Processing took: {} milliseconds", System.currentTimeMillis() - before);
    }

    public void destroy() {
    }
}
